import 'package:ad_common/third_ad.dart';
import 'package:ad_common/third_ad_instance.dart';
import 'package:ad_plugin/ad_source.dart';
import 'package:flutter/foundation.dart';

import 'ad_container.dart';
import 'ad_error.dart';
import 'ad_listener.dart';
import 'ad_manager.dart';

/// FileName banner_ad
/// @Author zhuqingfang
/// @Date 2022/10/8 11:39 上午
/// @Description banner ad
class BannerAd extends Ad{
  final AdLoadCallback<BannerAd> adLoadCallback;
  ContentCallback<BannerAd>? contentCallback;
  BannerAd._(
      {required String placementId,
        required this.adLoadCallback})
      : super(placementId: placementId);
  static load(
      {required String placementId,
        required double width,
        required double height,
        required AdLoadCallback<BannerAd> adLoadCallback}) {
    BannerAd bannerAd = BannerAd._(
        placementId: placementId, adLoadCallback: adLoadCallback);
    SourceAdType source;
    switch(AdGlobalParamsManager.instance.getAdSource()){

      case AdSource.topOn:
        source = SourceAdType.topOnBannerAd;
        break;
      case AdSource.google:
        source = SourceAdType.adMobBannerAd;
        break;
      default:
        source = SourceAdType.topOnBannerAd;
        break;
    }
    bannerAd.loadConfig(source);
    bannerAd.thirdAdParams = ThirdAdParams(
        appId: AdGlobalParamsManager.instance.getAdAppId(),
        appKey: AdGlobalParamsManager.instance.getAdAppKey(),
        placementId: placementId,
        width: width,
        height: height,
        thirdAdEventCallback:
            (AdCallbackEvent adCallbackEvent, String message,Object extraInfo) {
          debugPrint("ad callback $adCallbackEvent message:$message");
          switch(adCallbackEvent) {
            case AdCallbackEvent.adLoaded:
              bannerAd.adLoadCallback.onAdLoaded(bannerAd);
              break;
            case AdCallbackEvent.adLoadFail:
              LoadAdError loadAdError = LoadAdError(-1, message);
              bannerAd.adLoadCallback.onAdFailLoad(bannerAd,loadAdError);
              break;
            case AdCallbackEvent.adOnShow:
              bannerAd.contentCallback?.onAdShow(bannerAd);
              break;
            case AdCallbackEvent.adOnDismissed:
              bannerAd.contentCallback?.onAdDismiss(bannerAd);
              break;
            case AdCallbackEvent.adOnClicked:
              bannerAd.contentCallback?.onAdClick(bannerAd);
              break;
            default:
              LoadAdError loadAdError = LoadAdError(-1,message);
              bannerAd.adLoadCallback.onAdFailLoad(bannerAd,loadAdError);
              break;
          }
        });
    if (thirdAdInstance.adSourceMap.containsKey(bannerAd.sourceType)) {
      bannerAd.thirdAd = thirdAdInstance
          .adSourceMap[bannerAd.sourceType](bannerAd.thirdAdParams);
      bannerAd.thirdAd.load();
    }
  }
}